package uk.co.nazz.f21mc_a2.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

import uk.co.nazz.f21mc_a2.DiaryApplication;
import uk.co.nazz.f21mc_a2.R;
import uk.co.nazz.f21mc_a2.diary.Attendee;
import uk.co.nazz.f21mc_a2.diary.Diary;
import uk.co.nazz.f21mc_a2.utils.AttendeesAdapter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract.Attendees;
import android.provider.CalendarContract.Events;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * 
 * @author Andrew Stokes This class supports the UI for creating or editing
 *         diary events
 */
public class EventEditor extends Activity implements OnClickListener,
		OnItemClickListener, OnFocusChangeListener {

	private static final int PICKER_REQUEST_CODE = 4729;
	public static final String RECURRENCE_NONE = "NONE";
	private int thisYear;
	private int thisMonth;
	private int today;
	int thisHour;
	int thisMinute;

	private String eventId;

	private TextView startTime;
	private TextView startDate;

	private TextView endTime;
	private TextView endDate;
	private DatePickerDialog datePicker;
	private TimePickerDialog timePicker;

	private ImageButton startDateButton;
	private ImageButton startTimeButton;

	private ImageButton endDateButton;
	private ImageButton endTimeButton;

	private TextView titleText;
	private TextView descriptionText;
	private TextView locationText;
	private Button saveButton;

	private ImageButton addContactButton;

	private ArrayList<Attendee> attendees;
	private ListView attendeesListView;

	private AttendeesAdapter adapter;

	private Spinner recurrenceTypeSpinner;
	private Spinner recurrenceFrequencySpinner;

	private TextView recurrenceTypeSpinnerLabel;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			eventId = extras.getString("eventId");
		} else {
			eventId = "";
		}

		final Calendar calendar = Calendar.getInstance();
		thisYear = calendar.get(Calendar.YEAR);
		thisMonth = calendar.get(Calendar.MONTH);
		today = calendar.get(Calendar.DAY_OF_MONTH);
		thisHour = calendar.get(Calendar.HOUR_OF_DAY);
		thisMinute = calendar.get(Calendar.MINUTE);

		super.onCreate(savedInstanceState);
		setContentView(R.layout.editevent);

		startDate = (TextView) findViewById(R.id.newevent_startdate);
		startDate.setOnClickListener(this);
		startDateButton = (ImageButton) findViewById(R.id.newevent_imagebutton_startdate);
		startDateButton.setOnClickListener(this);

		startTime = (TextView) findViewById(R.id.newevent_starttime);
		startTime.setOnClickListener(this);
		startTimeButton = (ImageButton) findViewById(R.id.newevent_imagebutton_starttime);
		startTimeButton.setOnClickListener(this);

		endDate = (TextView) findViewById(R.id.newevent_enddate);
		endDate.setOnClickListener(this);
		endDateButton = (ImageButton) findViewById(R.id.newevent_imagebutton_enddate);
		endDateButton.setOnClickListener(this);

		endTime = (TextView) findViewById(R.id.newevent_endtime);
		endTime.setOnClickListener(this);
		endTimeButton = (ImageButton) findViewById(R.id.newevent_imagebutton_endtime);
		endTimeButton.setOnClickListener(this);

		// add focus changed listeners to validate any
		// text added to the time/date fields
		startDate.setOnFocusChangeListener(this);
		endDate.setOnFocusChangeListener(this);
		startTime.setOnFocusChangeListener(this);
		endTime.setOnFocusChangeListener(this);

		saveButton = (Button) findViewById(R.id.newevent_save_button);
		saveButton.setOnClickListener(this);

		titleText = (TextView) findViewById(R.id.newevent_event_title);
		descriptionText = (TextView) findViewById(R.id.newevent_description);
		locationText = (TextView) findViewById(R.id.newevent_event_location);

		addContactButton = (ImageButton) findViewById(R.id.newevent_imagebutton_contact);
		addContactButton.setOnClickListener(this);

		attendees = new ArrayList<Attendee>();

		attendeesListView = (ListView) findViewById(R.id.newevent_listview_attendees);

		adapter = new AttendeesAdapter(this,
				android.R.layout.simple_list_item_1, attendees);
		attendeesListView.setAdapter(adapter);

		attendeesListView.setOnItemClickListener(this);

		recurrenceTypeSpinner = (Spinner) findViewById(R.id.newevent_recurrencetype_spinner);
		recurrenceFrequencySpinner = (Spinner) findViewById(R.id.newevent_recurrencefreq_spinner);

		recurrenceFrequencySpinner.setEnabled(false);
		recurrenceFrequencySpinner.setVisibility(View.INVISIBLE);

		recurrenceTypeSpinnerLabel = (TextView) findViewById(R.id.newevent_recurrencefreq_label);

		recurrenceTypeSpinner = (Spinner) findViewById(R.id.newevent_recurrencetype_spinner);

		// add a listener to the recurrence type spinner to show/hide the
		// recurrence frequency spinner
		recurrenceTypeSpinner
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> adapterView,
							View arg1, int position, long l) {
						// if none selected in the type spinner hide the
						// frequency spinner
						if (position == 0) {
							recurrenceFrequencySpinner.setEnabled(false);
							recurrenceFrequencySpinner
									.setVisibility(View.INVISIBLE);
							recurrenceTypeSpinnerLabel
									.setVisibility(View.INVISIBLE);
						} else {
							// if an option (e.g. monthly, weekly etc.) is
							// selected in the type spinner show
							// the frequency spinner
							recurrenceFrequencySpinner.setEnabled(true);
							recurrenceFrequencySpinner
									.setVisibility(View.VISIBLE);
							recurrenceTypeSpinnerLabel
									.setVisibility(View.VISIBLE);
						}

					}

					// if nothing selected hide the frequency spinner
					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						recurrenceFrequencySpinner.setEnabled(false);
						recurrenceFrequencySpinner
								.setVisibility(View.INVISIBLE);
						recurrenceTypeSpinnerLabel
								.setVisibility(View.INVISIBLE);
					}

				});

		// allow the attendees list view to be scrolled while the
		// whole activity is also contained in
		attendeesListView.setOnTouchListener(new ListView.OnTouchListener() {
			@Override
			public boolean onTouch(View view, MotionEvent event) {
				int action = event.getAction();
				switch (action) {
				case MotionEvent.ACTION_DOWN:
					// Disallow parent ScrollView to intercept touch events.
					view.getParent().requestDisallowInterceptTouchEvent(true);
					break;

				case MotionEvent.ACTION_UP:
					// Allow parent ScrollView to intercept touch events.
					view.getParent().requestDisallowInterceptTouchEvent(false);
					break;
				}

				view.onTouchEvent(event);
				return true;
			}
		});

		if (eventId != null) {
			// if an eventId has been passed to this activity in the extras this
			// form is being used to edit an existing event prepopulate
			// the event fields with existing data
			populateForm();
		} else {
			setTitle("New Event");
		}

	}

	/**
	 * private method to prepopulate the form fields with the data for an
	 * existing event if this form is being used in edit mode
	 */
	private void populateForm() {
		// query the data for the event
		String[] projection = { Events.TITLE, Events.DTSTART, Events.DTEND,
				Events.DESCRIPTION, Events.EVENT_LOCATION, Events.RRULE };
		String selection = Events._ID + "=?";
		String[] seletionArgs = { eventId };

		Cursor cursor = getContentResolver().query(Events.CONTENT_URI,
				projection, selection, seletionArgs, null);
		if (cursor.moveToFirst()) {

			// set text fields
			titleText.setText(cursor.getString(cursor
					.getColumnIndex(Events.TITLE)));
			locationText.setText(cursor.getString(cursor
					.getColumnIndex(Events.EVENT_LOCATION)));
			descriptionText.setText(cursor.getString(cursor
					.getColumnIndex(Events.DESCRIPTION)));

			// set date and time fields
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy",
					Locale.UK);
			SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm",
					Locale.UK);

			Calendar start = Calendar.getInstance();
			start.setTimeInMillis(Long.parseLong(cursor.getString(cursor
					.getColumnIndex(Events.DTSTART))));
			startDate.setText(dateFormat.format(start.getTime()));
			startTime.setText(timeFormat.format(start.getTime()));

			Calendar end = Calendar.getInstance();
			end.setTimeInMillis(Long.parseLong(cursor.getString(cursor
					.getColumnIndex(Events.DTEND))));
			endDate.setText(dateFormat.format(end.getTime()));
			endTime.setText(timeFormat.format(end.getTime()));

			// set recurrence spinners
			String recurrence = cursor.getString(cursor
					.getColumnIndex(Events.RRULE));
			if (recurrence.length() > 0) {
				{
					String[] rule = recurrence.split("=|;");

					recurrenceFrequencySpinner.setEnabled(true);
					recurrenceFrequencySpinner.setVisibility(View.VISIBLE);
					recurrenceTypeSpinnerLabel.setVisibility(View.VISIBLE);
					if (rule.length == 4) {
						recurrenceTypeSpinner.setSelection(getIndex(
								recurrenceTypeSpinner, rule[1]));
						recurrenceFrequencySpinner.setSelection(getIndex(
								recurrenceFrequencySpinner, rule[3]));

					} else {
						recurrenceTypeSpinner.setSelection(getIndex(
								recurrenceTypeSpinner, rule[1]));
						recurrenceFrequencySpinner
								.setSelection(recurrenceFrequencySpinner
										.getCount() - 1);

					}

				}
			}

			// set the attendees ArrayList and ListView
			addExistingAttendees();

		}

	}

	// find the spinner selection based on text
	private int getIndex(Spinner spinner, String string) {
		int index = 0;

		for (int i = 0; i < spinner.getCount(); i++) {
			if (spinner.getItemAtPosition(i).equals(string)) {
				index = i;
			}
		}
		return index;
	}

	// add an OnDateSetListener listener to the start date picker to set
	// the text in the start date text field
	private DatePickerDialog.OnDateSetListener setStartDate = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			// DatePicker month is 0 based
			String d = String.format("%02d/%02d/%04d", day, month + 1, year);
			startDate.setText(d);
		}

	};

	// add an OnDateSetListener listener to the end date picker to set
	// the text in the end date text field
	private DatePickerDialog.OnDateSetListener setEndDate = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			// DatePicker month is 0 based
			String d = String.format("%02d/%02d/%04d", day, month + 1, year);
			endDate.setText(d);
		}

	};

	// add an OnTimeSetListener listener to the start time picker to set
	// the text in the time start text field
	private TimePickerDialog.OnTimeSetListener setStartTime = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hour, int minute) {
			String t = String.format("%02d:%02d", hour, minute);
			startTime.setText(t);

		}

	};

	// add an OnTimeSetListener listener to the end time picker to set
	// the text in the end time text field
	private TimePickerDialog.OnTimeSetListener setEndTime = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hour, int minute) {
			String t = String.format("%02d:%02d", hour, minute);
			endTime.setText(t);

		}

	};

	// start contactPicker dialog intent to get phone contacts in order to
	// choose attendees for the event
	public void contactPicker(View view) {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
		startActivityForResult(intent, PICKER_REQUEST_CODE);

	}

	// onClick listeners for form click events
	@Override
	public void onClick(View view) {
		if (view.getClass() == TextView.class) {
			if ((TextView) view == startDate) {
				datePicker = new DatePickerDialog(this, setStartDate, thisYear,
						thisMonth, today);
				datePicker.show();
			} else if ((TextView) view == endDate) {
				datePicker = new DatePickerDialog(this, setEndDate, thisYear,
						thisMonth, today);
				datePicker.show();
			} else if ((TextView) view == startTime) {
				timePicker = new TimePickerDialog(this, setStartTime, thisHour,
						thisMinute, true);
				timePicker.show();
			} else if ((TextView) view == endTime) {
				timePicker = new TimePickerDialog(this, setEndTime, thisHour,
						thisMinute, true);
				timePicker.show();
			}
		} else if (view.getClass() == ImageButton.class) {

			if ((ImageButton) view == startDateButton) {
				datePicker = new DatePickerDialog(this, setStartDate, thisYear,
						thisMonth, today);
				datePicker.show();
			} else if ((ImageButton) view == endDateButton) {
				datePicker = new DatePickerDialog(this, setEndDate, thisYear,
						thisMonth, today);
				datePicker.show();
			} else if ((ImageButton) view == startTimeButton) {
				timePicker = new TimePickerDialog(this, setStartTime, thisHour,
						thisMinute, true);
				timePicker.show();
			} else if ((ImageButton) view == endTimeButton) {
				timePicker = new TimePickerDialog(this, setEndTime, thisHour,
						thisMinute, true);
				timePicker.show();
			} else if ((ImageButton) view == addContactButton) {
				contactPicker(view);

			}

		} else if (view.getClass() == Button.class) {
			if ((Button) view == saveButton) {
				saveEvent();

			}
		}

	}

	// if the save button clicked
	private void saveEvent() {

		// validate the form fields
		Boolean formIsValid = true;
		String formErrors = "";
		if (titleText.getText().toString().length() < 1) {
			formErrors += "Title, ";
			formIsValid = false;
		}
		// check the start date
		Calendar start = formatDateTime(startDate.getText().toString(),
				startTime.getText().toString());
		if (start == null) {
			formErrors += "Start date/time, ";
			formIsValid = false;
		}
		// check the end date
		Calendar end = formatDateTime(endDate.getText().toString(), endTime
				.getText().toString());
		if (end == null) {
			formErrors += "End date/time, ";
			formIsValid = false;
		}

		if (end.getTimeInMillis() < start.getTimeInMillis()) {
			Toast toast = Toast
					.makeText(
							getApplicationContext(),
							"Please ensure that the event start is earlier than the event end",
							Toast.LENGTH_SHORT);
			toast.show();
			return;
		}
		if (!formIsValid) {
			// the form isn't valid, tell the user where they went wrong
			Toast toast = Toast.makeText(getApplicationContext(),
					"Please check the following form elements: " + formErrors,
					Toast.LENGTH_SHORT);
			toast.show();
		} else {
			try {
				// the form is valid create a new event
				// or update an existing one
				String recurrenceRule = formatRecurrenceString();
				String location = locationText.getText().toString();
				DiaryApplication application = (DiaryApplication) getApplication();
				Diary diary = application.getDiary();

				// get the values from the form
				String title = titleText.getText().toString();

				String description = descriptionText.getText().toString();
				Log.i("F21MC_2", "eventId" + eventId.length());
				// if the event is being modified then call the
				// update event method of the diary class
				if (eventId.length() > 0) {
					Log.i("F21MC_2", "Save new event");
					diary.updateEvent(title, start, end, description,
							recurrenceRule, attendees, location, eventId);
				} else {
					// otherwise it's a new so create a new event
					Log.i("F21MC_2", "Update existing event");
					diary.createEvent(title, start, end, description,
							recurrenceRule, attendees, location, this);
				}
				// if attendees have been added send them an email
				if (attendees.size() > 0) {
					emailAttendees(title, start, end, description,
							recurrenceRule, location);
				}
				finish();
			} catch (Exception e) {
				Log.v("F21MC_2", e.getMessage());
			}
		}

	}

	// format the string for event recurrences based on the user's selections in
	// the recurrence type and frequency spinners. If the recurrence option
	// 'None' was selected return an empty string

	private String formatRecurrenceString() {
		String rRule = "";
		Log.i("F21MC_2", "formatRecurrenceString started");
		if (recurrenceTypeSpinner.getSelectedItemPosition() != Spinner.INVALID_POSITION) {
			Log.i("F21MC_2", "recurrenceTypeSpinner valid");

			String recurrenceString = recurrenceTypeSpinner.getItemAtPosition(
					recurrenceTypeSpinner.getSelectedItemPosition()).toString();
			// if the default None selection has not bee specified for the
			// recurrence, format the recurrence type and frequency string
			if (!recurrenceString.equals(RECURRENCE_NONE)
					&& (recurrenceString.length() > 0)) {
				rRule = "FREQ=" + recurrenceString;

				// check to see if the number of occurrences spinner has a
				// valid selection and that the selection is not the
				// last - the infinite option
				if ((recurrenceFrequencySpinner.getSelectedItemPosition() != Spinner.INVALID_POSITION)
						&& (recurrenceFrequencySpinner
								.getSelectedItemPosition() != recurrenceFrequencySpinner
								.getCount() - 1)) {
					Log.i("F21MC_2", "recurrenceFrequencySpinner valid");
					rRule += ";COUNT="
							+ recurrenceFrequencySpinner.getItemAtPosition(
									recurrenceFrequencySpinner
											.getSelectedItemPosition())
									.toString();

				}
			}

		}
		return rRule;

	}

	// handle the data returned from the contactPicker dialog
	// get the contact's name, email and mobile number then
	// create an attendee object to match
	@Override
	protected void onActivityResult(int request, int result, Intent data) {
		if (result == RESULT_OK) {
			switch (request) {
			case PICKER_REQUEST_CODE:
				String emailAddress = "";
				String name = "";
				// get the URI of the selected contact
				Uri resultUri = data.getData();
				// strip off the ID of the contact
				String contactId = resultUri.getLastPathSegment();
				// query the android.provider.ContactsContract.Data content
				// provider for the details of the selected contact
				Cursor cur = getContentResolver().query(
						Data.CONTENT_URI,
						new String[] { Contacts._ID,
								Contacts.DISPLAY_NAME_PRIMARY },
						Data.CONTACT_ID + "=?",
						new String[] { String.valueOf(contactId) }, null);

				if (cur.moveToFirst()) {
					// get the Id, email address and name of of the contact
					int Id = Integer.parseInt(cur.getString(cur
							.getColumnIndex(Contacts._ID)));
					name = cur.getString(cur
							.getColumnIndex(Contacts.DISPLAY_NAME_PRIMARY));

					// get the contact's email address
					emailAddress = getAttendeeEmail(contactId);

					// add the contact to the ArrayList of attendees
					addAttendee(new Attendee(Id, name, emailAddress));
				}

				Log.v("F21MC_2", "Got a result: " + resultUri.toString());
			}
		} else {
			// something went wrong
			Log.w("F21MC_2", "Activity result not ok");
		}
	}

	// get the primary email address of a selected contact
	private String getAttendeeEmail(String contactId) {
		String emailAddress = "";
		Cursor emailCur = getContentResolver().query(
				ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
				ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
				new String[] { contactId }, null);
		while (emailCur.moveToNext()) {
			emailAddress = emailCur
					.getString(emailCur
							.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

		}
		emailCur.close();
		return emailAddress;
	}

	// Add the selected attendee to the ArrayList
	private void addAttendee(Attendee attendee) {
		// check to see if the contact has already added
		// using email address as a unique identifier
		boolean contactPresent = false;
		for (int i = 0; i < attendees.size(); i++) {
			if (attendees.get(i).getEmail().equals(attendee.getEmail()))
				contactPresent = true;
		}

		// if the contact not already present add it to the list of attendees
		if (!contactPresent) {
			Log.i("F21MC_2", "Attendee added - ID: " + attendee.getId());
			attendees.add(attendee);
			// notify that the model changed
			adapter.notifyDataSetChanged();
		}

	}

	// handle the onItemClick event of the attendees ListView
	// and remove a selected attendee from the attendees ArrayList
	@Override
	public void onItemClick(AdapterView<?> parent, final View view,
			int position, long id) {
		final Attendee item = (Attendee) parent.getItemAtPosition(position);
		view.animate().setDuration(1000).alpha(0).withEndAction(new Runnable() {
			@Override
			public void run() {
				try {
					attendees.remove(item);
					adapter.notifyDataSetChanged();
					view.setAlpha(1);
				} catch (Exception e) {
					Log.v("F21MC_2", e.getMessage());
				}
			}
		});
	}

	// format the time and date text fields as Calendar objects
	private Calendar formatDateTime(String date, String time) {

		Calendar dateTime;
		// do some initial validation by testing the date and time fields with
		// regular expressions
		if (Pattern.matches(("\\d\\d/\\d\\d/\\d\\d\\d\\d"), date)
				&& Pattern.matches(("\\d\\d:\\d\\d"), time)) {
			try {
				// if they look correct, chekc they can actually be parsed to
				// dates and times
				dateTime = Calendar.getInstance();

				String[] dates = date.split("/");
				int year = Integer.parseInt(dates[2]);
				int month = Integer.parseInt(dates[1]);
				int day = Integer.parseInt(dates[0]);

				String[] times = time.split(":");
				int hour = Integer.parseInt(times[0]);
				int minute = Integer.parseInt(times[1]);

				dateTime.set(year, month, day, hour, minute);
				Log.i("F21MC_2",
						"dateTime parse result: " + dateTime.toString());
			} catch (Exception e) {
				Log.i("F21MC_2", "Exception " + e.toString()
						+ " parsing date: " + date + " or time: " + time);
				dateTime = null;
			}
		} else {
			Log.i("F21MC_2", "Exception parsing date: " + date + " or time: "
					+ time);
			dateTime = null;
		}

		return dateTime;

	}

	@Override
	// Check the format of the strings in the date and time fields
	// if the string's don't match dd/dd/dddd for date or dd:dd for time
	// attempt to infer and set the correct values, if not possible set the
	// field to empty
	public void onFocusChange(View v, boolean hasFocus) {
		TextView tv = (TextView) v;
		String formattedText = "";
		if (!hasFocus) {
			if (tv == startDate || tv == endDate) {

				try {
					String dateString = tv.getText().toString();
					// split the string on these separators
					String[] dateArray = dateString.split("\\.|-|/");
					int d = Integer.parseInt(dateArray[0]);
					int m = Integer.parseInt(dateArray[1]);
					int y = Integer.parseInt(dateArray[2]);

					formattedText = String.format("%02d/%02d/%04d", d, m, y);
					// try to parse the formated text as a date
					// if it fails the catch block will reset the date field
					SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy",
							Locale.UK);
					sdf.setLenient(false);
					if (sdf.parse(formattedText, new ParsePosition(0)) != null) {
						tv.setText(formattedText);
					} else {
						Log.i("F21MC_2", "Incorrectly formatted string "
								+ " date string: " + formattedText);
						tv.setText("");
					}

				} catch (Exception e) {
					Log.i("F21MC_2", "Incorrectly formatted string "
							+ " date string: " + tv.getText());
					tv.setText("");
				}
			} else if (tv == startTime || tv == endTime) {
				try {
					String[] time = tv.getText().toString().split(":");
					int h = Integer.parseInt(time[0]);
					int m = Integer.parseInt(time[1]);
					if (((h < 24 && m < 60) || (h == 24 && m == 0))
							&& (h > -1 && m > -1)) {
						formattedText = String.format("%02d:%02d", h, m);
						tv.setText(formattedText);
					} else {
						Log.i("F21MC_2", "Incorrectly formatted string "
								+ " time string: " + time);
						tv.setText("");

					}

				} catch (Exception e) {
					Log.i("F21MC_2", "Incorrectly formatted string, error: "
							+ e.getMessage() + " input string: " + tv.getText());
					tv.setText("");
				}
			}
		}

	}

	// generate an iCal file and return path to it. If iCal file generation
	// fails return empty path string
	private String generateIcal(String title, String location, Calendar start,
			Calendar end) {
		// create an iCal file to attach to the email
		String fileName = "F21MC_2.ics";
		Log.i("F21MC_2", "Starting to create the iCal");
		String uid = System.currentTimeMillis() + "@f21mc.nazz.co.uk";
		String rRule = formatRecurrenceString();
		// format a string with the iCal data
		String iCal = "BEGIN:VCALENDAR\r\n"
				+ "VERSION:2.0\r\n"
				+ "PRODID:-//F21MC_2.nazz.co.uk//F21MC Assignment 2//EN\r\n"
				+ "BEGIN:VEVENT\r\n"
				+ "UID:"
				+ uid
				+ "\r\n"
				+ "DTSTAMP:"
				+ new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'")
						.format(new Date())
				+ "\r\n"
				+ "DTSTART:"
				+ new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'").format(start
						.getTime())
				+ "\r\n"
				+ "DTEND:"
				+ new SimpleDateFormat("yyyyMMdd'T'hhmmss'Z'").format(end
						.getTime()) + "\r\n" + "SUMMARY:" + title + "\r\n"
				+ "LOCATION:" + location + "\r\n";
		if (rRule.length() > 0) {
			iCal += "RRULE:" + rRule + "\r\n";

		}
		iCal += "END:VEVENT\r\n" + "END:VCALENDAR\r\n";
		Log.i("F21MC_2", "iCal String:- " + iCal);

		try {
			// write the string to a file to a location which can be accessed by
			// the email intent used to send event reminders
			FileOutputStream fos = openFileOutput(fileName, MODE_WORLD_READABLE);
			PrintStream ps = new PrintStream(fos);
			ps.print(iCal);
			ps.close();

			Log.i("F21MC_2", "iCal file written!");

		} catch (IOException e) {
			Log.v("F21MC_2", "Error creating iCal file: " + e.toString());
			fileName = "";
		}

		return fileName;
	}

	// send the email message using an emailIntent and attach the iCal file
	private void emailAttendees(String title, Calendar start, Calendar end,
			String description, String recurrenceRule, String location) {
		String[] emailAddresses = new String[attendees.size()];
		int i = 0;
		for (Attendee a : attendees) {
			emailAddresses[i++] = a.getEmail();
		}
		Log.i("F21MC_2", "Starting formatting body");
		String emailBody = "";

		// format the start and end dates
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm",
				Locale.UK);
		emailBody += "Event start: " + sdf.format(start.getTime()) + "\n";
		emailBody += "Event end: " + sdf.format(end.getTime()) + "\n";

		emailBody += "Location: " + location + "\n";
		Log.i("F21MC_2", "Email constructor - start recurrence");
		// format the recurrence rules for the email body

		if (recurrenceRule.length() > 1) {
			emailBody += "Recurrence: " + recurrenceRule + "\n";
		}

		emailBody += "Description:- \n " + description + "\n";

		Log.i("F21MC_2", "Starting email intent");
		try {
			final Intent emailIntent = new Intent(
					android.content.Intent.ACTION_SEND);

			// add the email address
			emailIntent.setType("plain/text");
			Log.i("F21MC_2", "EMAILS:- " + emailAddresses[0]);
			if (emailAddresses != null)
				emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
						emailAddresses);
			// add the email subject
			Log.i("F21MC_2", "Title:- " + title);
			if (title != null)
				emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
						title);
			// add the body
			Log.i("F21MC_2", "Body:- " + emailBody);
			if (emailBody != null)
				emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
						emailBody);
			// if the path to the iCal isn't empty attach the file

			String iCalFile = generateIcal(title, location, start, end);
			if (iCalFile.length() > 0) {
				// add the iCal attachment
				Uri uri = Uri.fromFile(new File(getFilesDir(), iCalFile));
				emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
			}

			// send the email
			Log.i("F21MC_2", "Sending...");
			startActivity(Intent.createChooser(emailIntent, "Send email..."));

		} catch (ActivityNotFoundException e) {
			Log.v("F21MC", "Problem sending email: " + e.getMessage());
		}
	}

	// if the form is being used to edit existing events query and add these
	// attendees to the attendees ListView
	private void addExistingAttendees() {

		// query for the attendees
		String[] attendeeProjection = { Attendees.ATTENDEE_NAME,
				Attendees.ATTENDEE_EMAIL, Attendees.ATTENDEE_IDENTITY };
		String attendeeSelection = Attendees.EVENT_ID + "=?";
		String[] attendeeseletionArgs = { eventId };

		Cursor attendeeCursor = getContentResolver().query(
				Attendees.CONTENT_URI, attendeeProjection, attendeeSelection,
				attendeeseletionArgs, null);
		int i = 1;
		while (attendeeCursor.moveToNext()) {
			String name = attendeeCursor.getString(attendeeCursor
					.getColumnIndex(Attendees.ATTENDEE_NAME));
			String email = attendeeCursor.getString(attendeeCursor
					.getColumnIndex(Attendees.ATTENDEE_EMAIL));
			if (name != null) {
				attendees.add(new Attendee(i, name, email));
				adapter.notifyDataSetChanged();
				i++;
			}
		}

	}

}
